import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { UploadResult, GenerationItem } from '../components';
import { fadeIn, scaleIn, bounceIn } from '../utils/animations';
import { useComfyUI, TaskStatus } from '../contexts/ComfyUIContext';
import { historyManager, type GenerationHistoryItem } from '../services/historyManager';
import './Generate.css';

interface GenerateState {
  prompt: string;
  activeType: string;
  selectedFeature: string;
  selectedBusiness: string;
  uploadedImage?: string;
}

const History: React.FC = () => {
  const navigate = useNavigate();
  
  // ComfyUI相关状态
  const { currentTask, isGenerating } = useComfyUI();
  
  const [result, setResult] = useState<string | null>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [showUploadResult, setShowUploadResult] = useState(false);
  
  // 生成状态管理
  const [currentHistoryItem, setCurrentHistoryItem] = useState<GenerationHistoryItem | null>(null);
  const [historyList, setHistoryList] = useState<GenerationHistoryItem[]>([]);
  const emptyStateRef = useRef<HTMLDivElement | null>(null);
  const generatingRef = useRef<HTMLDivElement | null>(null);
  const resultRef = useRef<HTMLDivElement | null>(null);

  // 页面加载动画
  useEffect(() => {
    if (emptyStateRef.current) {
      fadeIn(emptyStateRef.current, { delay: 0.3 });
    }
  }, []);

  // 页面初始化时加载历史记录
  useEffect(() => {
    const loadedHistoryList = historyManager.getHistoryList();
    setHistoryList(loadedHistoryList);
    
    if (loadedHistoryList.length > 0) {
      // 获取最新的历史记录项
      const latestItem = loadedHistoryList[loadedHistoryList.length - 1];
      setCurrentHistoryItem(latestItem);
      
      // 根据历史记录的状态设置结果状态
      if (latestItem.status === 'completed') {
        setResult('生成完成！');
        if (latestItem.generatedImages && latestItem.generatedImages.length > 0) {
          setImagePreview(latestItem.generatedImages[0]);
        }
      } else if (latestItem.status === 'failed') {
        setResult('生成失败');
      }
      
      console.log('加载历史记录:', latestItem);
    }
  }, []);

  // 生成状态动画
  useEffect(() => {
    if (isGenerating && generatingRef.current) {
      bounceIn(generatingRef.current);
    }
  }, [isGenerating]);

  // 结果状态动画
  useEffect(() => {
    if (result && resultRef.current) {
      scaleIn(resultRef.current, { delay: 0.2 });
    }
  }, [result]);


  // 监听ComfyUI任务状态变化
  useEffect(() => {
    if (currentTask && currentHistoryItem) {
      // 防止重复更新：如果状态已经是完成状态，不再更新
      if (currentTask.status === TaskStatus.COMPLETED && currentTask.result) {
        if (currentHistoryItem.status !== 'completed') {
          setResult('生成完成！');
          setImagePreview(currentTask.result[0]);
          
          // 更新历史记录
          historyManager.updateHistoryItem(currentHistoryItem.id, {
            status: 'completed',
            uploadingStatus: '生成完成！',
            generatedImages: currentTask.result
          });
          
          // 更新当前历史记录项
          const updatedItem = { ...currentHistoryItem, 
            status: 'completed' as const,
            uploadingStatus: '生成完成！',
            generatedImages: currentTask.result
          };
          setCurrentHistoryItem(updatedItem);
          
          // 重新加载历史记录列表
          const updatedHistoryList = historyManager.getHistoryList();
          setHistoryList(updatedHistoryList);
        }
        
      } else if (currentTask.status === TaskStatus.FAILED) {
        if (currentHistoryItem.status !== 'failed') {
          setResult(`生成失败: ${currentTask.error || '未知错误'}`);
          
          // 更新历史记录
          historyManager.updateHistoryItem(currentHistoryItem.id, {
            status: 'failed',
            uploadingStatus: `生成失败: ${currentTask.error || '未知错误'}`
          });
          
          // 更新当前历史记录项
          const updatedItem = { ...currentHistoryItem, 
            status: 'failed' as const,
            uploadingStatus: `生成失败: ${currentTask.error || '未知错误'}`
          };
          setCurrentHistoryItem(updatedItem);
          
          // 重新加载历史记录列表
          const updatedHistoryList = historyManager.getHistoryList();
          setHistoryList(updatedHistoryList);
        }
        
      } else if (currentTask.status === TaskStatus.RUNNING) {
        if (currentHistoryItem.status !== 'uploading') {
          
          // 更新历史记录
          historyManager.updateHistoryItem(currentHistoryItem.id, {
            status: 'uploading',
            uploadingStatus: '正在生成中'
          });
          
          // 更新当前历史记录项
          const updatedItem = { ...currentHistoryItem, 
            status: 'uploading' as const,
            uploadingStatus: '正在生成中'
          };
          setCurrentHistoryItem(updatedItem);
          
          // 重新加载历史记录列表
          const updatedHistoryList = historyManager.getHistoryList();
          setHistoryList(updatedHistoryList);
        }
      }
    }
  }, [currentTask, currentHistoryItem]);



  const handleEdit = (imageUrl: string, historyItem?: GenerationHistoryItem) => {
    console.log('编辑图片:', imageUrl);
    
    // 准备跳转参数
    const navigateState: GenerateState = {
      prompt: historyItem?.context.prompt || '',
      activeType: historyItem?.context.activeType || 'image',
      selectedFeature: historyItem?.context.selectedFeature || '图片生成',
      selectedBusiness: historyItem?.context.selectedBusiness || '瑜伽',
      uploadedImage: imageUrl
    };
    
    // 跳转到Generate页面
    navigate('/generate', { state: navigateState });
  };

  const handleRegenerate = (historyItem?: GenerationHistoryItem) => {
    console.log('重新生成');
    
    if (!historyItem) {
      console.error('没有找到历史记录项');
      return;
    }
    
    // 准备跳转参数
    const navigateState: GenerateState = {
      prompt: historyItem.context.prompt || '',
      activeType: historyItem.context.activeType || 'image',
      selectedFeature: historyItem.context.selectedFeature || '图片生成',
      selectedBusiness: historyItem.context.selectedBusiness || '瑜伽',
      uploadedImage: historyItem.imageUrls[0]
    };
    
    // 跳转到Generate页面
    navigate('/generate', { state: navigateState });
  };

  const handleDownload = () => {
    console.log('下载图片');
    // TODO: 实现下载功能
  };

  const handleShare = () => {
    console.log('分享图片');
    // TODO: 实现分享功能
  };


  const handleDeleteItem = (id: string) => {
    console.log('删除项目:', id);
    historyManager.deleteHistoryItem(id);
    const updatedHistoryList = historyManager.getHistoryList();
    setHistoryList(updatedHistoryList);
    
    // 如果删除的是当前项目，清空当前项目
    if (currentHistoryItem && currentHistoryItem.id === id) {
      setCurrentHistoryItem(null);
    }
  };

  return (
    <main className="main-content">
      {/* 主内容区域 */}
      <div className="generate-main">
        {historyList.length > 0 ? (
          <div className="history-list">
            {historyList.map((item) => (
              <GenerationItem
                key={item.id}
                id={item.id}
                date={item.date}
                imageUrls={item.imageUrls}
                format={item.format}
                aspectRatio={item.aspectRatio}
                resolution={item.resolution}
                status={item.status}
                uploadingStatus={item.uploadingStatus}
                generatedImages={item.generatedImages}
                prompt={item.context.prompt}
                onEdit={item.status !== 'uploading' ? () => handleEdit(item.imageUrls[0], item) : undefined}
                onRegenerate={item.status !== 'uploading' ? () => handleRegenerate(item) : undefined}
                onDelete={handleDeleteItem}
                onImageClick={item.status === 'completed' ? (imageUrl, imageIndex) => {
                  console.log('点击了生成的图片:', imageUrl, imageIndex);
                  setImagePreview(imageUrl);
                  setShowUploadResult(true);
                } : undefined}
              />
            ))}
          </div>
        ) : (
          <div className="empty-state" ref={emptyStateRef}>
            <p className="empty-text">暂未找到相关内容</p>
          </div>
        )}
      </div>

      {/* 上传结果组件 - 只在有图片预览时显示 */}
      {showUploadResult && imagePreview && currentHistoryItem && (
        <UploadResult
          imagePreview={imagePreview}
          onEdit={() => handleEdit(imagePreview, currentHistoryItem)}
          onRegenerate={() => handleRegenerate(currentHistoryItem)}
          onDownload={handleDownload}
          onShare={handleShare}
          onClose={() => setShowUploadResult(false)}
          isVisible={showUploadResult}
          prompt={currentHistoryItem.context.prompt}
          format={currentHistoryItem.format}
          aspectRatio={currentHistoryItem.aspectRatio}
          resolution={currentHistoryItem.resolution}
        />
      )}

      {/* LLM 面板 */}
      {/* <LLMPanel
        isVisible={showLLMPanel}
        onClose={() => setShowLLMPanel(false)}
        onSendMessage={handleLLMSend}
      /> */}

      {/* 底部输入框 */}
      {/* <div className="generation-card-container">
        <GenerationCard
          prompt={prompt}
          setPrompt={setPrompt}
          activeType={activeType}
          setActiveType={setActiveType}
          selectedFeature={selectedFeature}
          setSelectedFeature={setSelectedFeature}
          selectedBusiness={selectedBusiness}
          setSelectedBusiness={setSelectedBusiness}
          onGenerate={handleGenerate}
          onOpenLLM={() => setShowLLMPanel(true)}
          onImageUpload={handleImageUpload}
          uploadedImage={uploadedImage}
          width='42vw'
          onSmartPromptChange={setIsSmartPrompt}
        />
      </div> */}
    </main>
  );
};

export default History;